var bcrypt = dcodeIO.bcrypt;

function signup() {
    const name = document.getElementById('newname').value;
    const email = document.getElementById('newemail').value;
    const password1 = document.getElementById('newpassword1').value;
    const password2 = document.getElementById('newpassword2').value;

    if (!document.getElementById("termsCheck").checked) {
        alert("Please accept the term");
        return;
    }
    users = JSON.parse(localStorage.getItem("users"));
    if (users === null)    //if there are no users yet
        users = [];          //initialize it to empty
    if (users.find(u => u.email === email)) {
        alert("Your email already exists");
        return;
    }

    if (password1 === password2) {
        const salt = bcrypt.genSaltSync(10);
        const hashedPassword = bcrypt.hashSync(password1, salt);

        const Height=0;
        const Weight=0;
        users.push({ 
            name, 
            Height,
            Weight,
            email, 
            password: hashedPassword,
            day:0, 
            history:[] 
        });
        alert('User registered with hashed password. Welcome ' + name);
        localStorage.setItem("users", JSON.stringify(users));
        window.location.href = "Times.html";
    } else {
        alert('Passwords do not match!');
    }
    
}

function login() {
    users = JSON.parse(localStorage.getItem("users"));
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    const user = users.find(u => u.email === email);
    if (user && bcrypt.compareSync(password, user.password)) {
        alert('Login successful! for ' + user.name);
        localStorage.setItem("loggedinUser", JSON.stringify(user));
        window.location.href = "Times.html";
    } else {
        alert('Login failed.');
    }
}